package com.example.juc;

import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadFactory;

class MyThreadFactory2 implements ThreadFactory {
    private static final ThreadFactory INSTANCE = new MyThreadFactory2();
    private static final String TITLE = "thread-";
    private static int count = 0;
    private MyThreadFactory2(){}
    @Override
    public Thread newThread(Runnable r) {
        try {
            Class<?> clazz = Class.forName("java.lang.Thread");
            Constructor<?> constructor = clazz.getConstructor(Runnable.class, String.class);
            return (Thread) constructor.newInstance(r, TITLE + count++);
        } catch (Exception e) {
            return null;
        }
    }
    public static ThreadFactory getInstance() {
        return INSTANCE;
    }
}
public class ThreadFactoryTest2 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Thread thread = MyThreadFactory.getInstance().newThread(() -> {
                System.out.println("多线程执行: " + Thread.currentThread().getName());
            });
            thread.start();
        }
    }
}
